package unsplash;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Unsplash {
    private static final String client_id = "6f65f40b86d75ce605cc1029a9ae2eaf3e9f0396e6f650df0ed71da04a611ab6";
    private static final String unsplash_api_url = "https://api.unsplash.com/";

    private static String getRandomPhotosUrl(int count) {
        return Unsplash.unsplash_api_url + "photos/random?"
                + "featured&orientation=landscape"
                + "&count=" + count + "&client_id=" + Unsplash.client_id;
    }

    private static List<Photo> photosInfoToPhotosList(JSONArray photosInfo) throws JSONException {
        List<Photo> photos = Collections.synchronizedList(new LinkedList<Photo>());
        for (int i = 0; i < photosInfo.length(); i++) {
            JSONObject item = photosInfo.getJSONObject(i);
            if (item.getDouble("width") / item.getDouble("height") > 1.6) {
                continue;
            }
            Photo photo = new Photo(
                    item.getString("id"),
                    item.getJSONObject("links").getString("download"),
                    item.getJSONObject("urls").getString("regular")
            );
            photos.add(photo);
        }
        return photos;
    }

    public static List<Photo> getRandomPhotos(int count) throws IOException, JSONException {
        String url = getRandomPhotosUrl(count);
        JSONArray result;
        result = Api.readJsonArrayFromUrl(url);
        JSONArray photosInfo = result;
        return photosInfoToPhotosList(photosInfo);
    }
}
